#include <cassert>
#include <sstream>

#include "DXImageView.h"
#include "DX.h"
#include "DXImage.h"
#include "DXWindow.h"
#include "FourPointsPrimitive.h"

DXImageView::DXImageView( const MRect& rect, DXImage* image ) : View( rect ), alpha( 0xff )
{
	setImage( image );
}

DXImageView::~DXImageView()
{
	
}

void DXImageView::update( )
{
	D3DXMATRIX mTransf;
	D3DXVECTOR2 scale, transl;

	MRect clientRect = window()->getClientRect();
	float kx = 2.0f / clientRect.width();
	float ky = 2.0f / clientRect.height();

	scale.x = ( rect().width() ) / clientRect.width();
	scale.y = ( rect().height() ) / clientRect.height();
	transl.x = ( rect().width() ) / 2.0f * kx - 1.0f + rect().x() * kx;
	transl.y = ( rect().height() ) / 2.0f * ky - 1.0f + rect().y() * ky;
	
	D3DXMatrixTransformation2D( &mTransf, 0, 0, &scale, 0, 0, &transl );
	
	DXWindow* w = ( DXWindow* )window();

	DX::_()->device->SetTransform( D3DTS_WORLD, &mTransf );

		
	DX::_()->device->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
	DX::_()->device->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
	DX::_()->device->SetSamplerState( 0, D3DSAMP_MIPFILTER, D3DTEXF_NONE );
	

	DX::_()->device->SetTexture( 0, _image->texture() );
	
	DWORD value;

	DX::_()->device->GetTextureStageState( 0, D3DTSS_COLORARG1, &value );
	if ( value != D3DTA_TEXTURE ) DX::_()->device->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
	
	DX::_()->device->GetTextureStageState( 0, D3DTSS_COLOROP, &value );
	if ( value != D3DTOP_SELECTARG1 ) DX::_()->device->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
	
	DX::_()->device->SetRenderState( D3DRS_ALPHABLENDENABLE, true );
	DX::_()->device->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
	DX::_()->device->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD );
	DX::_()->device->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );

	DX::_()->device->SetFVF( LCVertexTexture::FORMAT );
	DX::_()->device->SetStreamSource( 0, FourPointsPrimitive::_()->buffer(), 0, sizeof( LCVertexTexture ) );
	DX::_()->device->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2 );

	DX::_()->device->SetRenderState( D3DRS_ALPHABLENDENABLE, false );

	DX::_()->device->SetTransform( D3DTS_WORLD, D3DXMatrixIdentity( &mTransf ) );

	__super::update();
}

void DXImageView::setImage( DXImage* image )
{
	assert( image );

	if ( _image != image )
	{
		_image = image;
	}
}

#ifdef _DEBUG

//std::wstring DXImageView::description()
//{
//	std::wstring ret;
//	std::wostringstream st;
//	st << "DXImageView:" << " x = " << rect().x() << " y = " << rect().y() << " w = " << rect().width() << " h = " << rect().height() << std::endl;
//	ret += st.str();
//	return ret;
//}

#endif